<template>
  <div class="app-container">
    <!-- 页面标题 -->
    <div class="page-title-container">
      <div class="page-title">
        <el-icon class="icon"><Collection /></el-icon>
        <span>字典管理</span>
      </div>
    </div>

    <el-card class="list-card">
      <!-- 搜索区域 -->
      <div class="filter-container">
        <el-form :model="queryParams" ref="queryForm" :inline="true" class="search-form">
          <el-form-item class="search-item">
            <el-input
              v-model="queryParams.name"
              placeholder="字典名称"
              clearable
              prefix-icon="Search"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item class="search-item">
            <el-input
              v-model="queryParams.code"
              placeholder="字典编码"
              clearable
              prefix-icon="DocumentCopy"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item class="action-buttons">
            <el-button type="primary" @click="handleQuery" plain>
              <el-icon><Search /></el-icon>查询
            </el-button>
            <el-button @click="resetQuery" plain>
              <el-icon><Refresh /></el-icon>重置
            </el-button>
          </el-form-item>
          <el-form-item class="add-button-item">
            <el-button
              type="primary"
              class="add-main-button"
              :icon="Plus"
              @click="handleAdd"
            >
              添加字典
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="categoryList"
        border
        stripe
        highlight-current-row
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="name" label="字典名称" min-width="120" :show-overflow-tooltip="true" />
        <el-table-column prop="code" label="字典编码" min-width="120" :show-overflow-tooltip="true" />
        <el-table-column prop="remark" label="备注" min-width="150" :show-overflow-tooltip="true" />
        <el-table-column prop="createTime" label="创建时间" min-width="160" align="center" :formatter="dateTimeFormatter" />
        <el-table-column label="操作" fixed="right" width="220" align="center">
          <template #default="scope">
            <el-tooltip content="编辑" placement="top">
              <el-button
                type="primary"
                link
                :icon="Edit"
                @click="handleUpdate(scope.row)"
              />
            </el-tooltip>
            <el-tooltip content="字典项管理" placement="top">
              <el-button
                type="success"
                link
                :icon="View"
                @click="handleViewItems(scope.row)"
              />
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button
                type="danger"
                link
                :icon="Delete"
                @click="handleDelete(scope.row)"
              />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.size"
          :page-sizes="[10, 20, 30, 50]"
          :small="false"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加或修改字典大类对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      append-to-body
      destroy-on-close
    >
      <el-form ref="categoryFormRef" :model="form" :rules="rules" label-width="80px" status-icon>
        <el-form-item label="字典名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入字典名称" />
        </el-form-item>
        <el-form-item label="字典编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入字典编码" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 字典项管理对话框 -->
    <el-dialog
      :title="currentCategory.name"
      v-model="itemDialogVisible"
      width="850px"
      append-to-body
      destroy-on-close
      class="item-dialog"
    >
      <!-- 字典项数据表格 -->
      <div class="item-table-container">
        <!-- 顶部工具栏 -->
        <div class="header-toolbar">
          <!-- 搜索区域 -->
          <div class="search-container">
            <el-form :model="itemQueryParams" ref="itemQueryForm" :inline="true" class="search-form">
              <el-form-item class="search-item">
                <el-input
                  v-model="itemQueryParams.name"
                  placeholder="字典项名称"
                  clearable
                  prefix-icon="Search"
                  @keyup.enter="handleItemQuery"
                />
              </el-form-item>
              <el-form-item class="search-item">
                <el-input
                  v-model="itemQueryParams.code"
                  placeholder="字典项编码"
                  clearable
                  prefix-icon="DocumentCopy"
                  @keyup.enter="handleItemQuery"
                />
              </el-form-item>
              <el-form-item class="action-buttons">
                <el-button type="primary" @click="handleItemQuery" plain>
                  <el-icon><Search /></el-icon>查询
                </el-button>
                <el-button @click="resetItemQuery" plain>
                  <el-icon><Refresh /></el-icon>重置
                </el-button>
              </el-form-item>
              <el-form-item class="add-button-item">
                <el-button 
                  type="primary" 
                  :icon="Plus" 
                  @click="handleAddItem" 
                  class="add-item-button"
                >
                  添加字典项
                </el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>

        <!-- 字典项数据表格 -->
        <el-table
          v-loading="itemLoading"
          :data="itemList"
          border
          stripe
          highlight-current-row
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column prop="id" label="ID" width="70" align="center" />
          <el-table-column prop="name" label="字典项名称" min-width="120" :show-overflow-tooltip="true" />
          <el-table-column prop="code" label="字典项编码" min-width="120" :show-overflow-tooltip="true" />
          <el-table-column prop="sort" label="排序" width="70" align="center">
            <template #default="scope">
              <el-tag type="info" effect="plain">{{ scope.row.sort }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" min-width="150" :show-overflow-tooltip="true" />
          <el-table-column prop="createTime" label="创建时间" min-width="160" align="center" :formatter="dateTimeFormatter" />
          <el-table-column label="操作" fixed="right" width="120" align="center">
            <template #default="scope">
              <el-tooltip content="编辑" placement="top">
                <el-button
                  type="primary"
                  link
                  :icon="Edit"
                  @click="handleUpdateItem(scope.row)"
                />
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button
                  type="danger"
                  link
                  :icon="Delete"
                  @click="handleDeleteItem(scope.row)"
                />
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>

        <!-- 字典项分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="itemQueryParams.page"
            v-model:page-size="itemQueryParams.size"
            :page-sizes="[10, 20, 30, 50]"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="itemTotal"
            @size-change="handleItemSizeChange"
            @current-change="handleItemCurrentChange"
          />
        </div>
      </div>
    </el-dialog>

    <!-- 添加或修改字典项对话框 -->
    <el-dialog
      :title="itemFormTitle"
      v-model="itemFormVisible"
      width="500px"
      append-to-body
      destroy-on-close
    >
      <el-form ref="itemFormRef" :model="itemForm" :rules="itemRules" label-width="100px" status-icon>
        <el-form-item label="所属字典" prop="categoryId">
          <el-input v-model="currentCategory.name" disabled>
            <template #prefix>
              <el-icon><Collection /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="字典项名称" prop="name">
          <el-input v-model="itemForm.name" placeholder="请输入字典项名称" />
        </el-form-item>
        <el-form-item label="字典项编码" prop="code">
          <el-input v-model="itemForm.code" placeholder="请输入字典项编码" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="itemForm.sort" :min="0" :max="999" controls-position="right" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="itemForm.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="itemFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitItemForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getDictCategoryPage, 
  createDictCategory, 
  updateDictCategory, 
  deleteDictCategory,
  getDictItemPage,
  createDictItem,
  updateDictItem,
  deleteDictItem
} from '@/api/dict'
import { 
  Search, 
  Refresh, 
  Plus, 
  Edit, 
  Delete, 
  View, 
  Collection,
  DocumentCopy
} from '@element-plus/icons-vue'

const loading = ref(false)
const categoryList = ref([])
const total = ref(0)
const selectedRows = ref([])
const dialogVisible = ref(false)
const categoryFormRef = ref(null)
const queryForm = ref(null)

// 字典项管理相关
const itemDialogVisible = ref(false)
const itemFormVisible = ref(false)
const itemLoading = ref(false)
const itemList = ref([])
const itemTotal = ref(0)
const itemFormRef = ref(null)
const itemQueryForm = ref(null)
const currentCategory = reactive({
  id: '',
  name: ''
})

// 查询参数
const queryParams = reactive({
  page: 1,
  size: 10,
  name: '',
  code: ''
})

// 字典项查询参数
const itemQueryParams = reactive({
  page: 1,
  size: 10,
  name: '',
  code: '',
  categoryId: ''
})

// 表单参数
const form = reactive({
  id: undefined,
  name: '',
  code: '',
  remark: ''
})

// 字典项表单参数
const itemForm = reactive({
  id: undefined,
  categoryId: '',
  name: '',
  code: '',
  sort: 0,
  remark: ''
})

// 表单校验规则
const rules = {
  name: [
    { required: true, message: '字典名称不能为空', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '字典编码不能为空', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
    { pattern: /^[A-Z_]+$/, message: '编码只能包含大写字母和下划线', trigger: 'blur' }
  ],
}

// 字典项表单校验规则
const itemRules = {
  name: [
    { required: true, message: '字典项名称不能为空', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '字典项编码不能为空', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' },
    { pattern: /^[A-Z_]+$/, message: '编码只能包含大写字母和下划线', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '排序不能为空', trigger: 'blur' }
  ]
}

// 计算属性
const dialogTitle = computed(() => {
  return form.id ? '编辑字典' : '添加字典'
})

// 字典项对话框标题
const itemFormTitle = computed(() => {
  return itemForm.id ? '编辑字典项' : '添加字典项'
})

// 日期格式化
const dateTimeFormatter = (row, column, cellValue) => {
  if (!cellValue) {
    return ''
  }
  return cellValue
}

// 初始化
onMounted(() => {
  getList()
})

// 获取字典大类列表
const getList = () => {
  loading.value = true
  getDictCategoryPage(queryParams)
    .then(response => {
      // 根据响应数据结构灵活处理
      let records = []
      let totalCount = 0
      
      if (response.data && response.data.list && Array.isArray(response.data.list)) {
        // 后端实际返回的格式: { code: 200, message: "操作成功", data: { list: [], total: 3 } }
        records = response.data.list
        totalCount = response.data.total || 0
      } else if (response.data && Array.isArray(response.data.records)) {
        // 标准分页格式 { data: { records: [], total: 10 } }
        records = response.data.records
        totalCount = response.data.total || 0
      } else if (Array.isArray(response.data)) {
        // 直接数组格式 { data: [] }
        records = response.data
        totalCount = response.data.length
      } else if (response.records && Array.isArray(response.records)) {
        // 无嵌套的分页格式 { records: [], total: 10 }
        records = response.records
        totalCount = response.total || 0
      }
      
      // 设置数据
      categoryList.value = records
      total.value = totalCount
    })
    .catch(error => {
      console.error('获取字典列表失败:', error)
      ElMessage.error('获取字典列表失败: ' + (error.message || '未知错误'))
    })
    .finally(() => {
      loading.value = false
    })
}

// 查询按钮操作
const handleQuery = () => {
  queryParams.page = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryForm.value?.resetFields()
  queryParams.page = 1
  getList()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 每页数量变化
const handleSizeChange = (val) => {
  queryParams.size = val
  getList()
}

// 页码变化
const handleCurrentChange = (val) => {
  queryParams.page = val
  getList()
}

// 表单重置
const resetForm = () => {
  form.id = undefined
  form.name = ''
  form.code = ''
  form.remark = ''
  if (categoryFormRef.value) {
    categoryFormRef.value.resetFields()
  }
}

// 新增按钮操作
const handleAdd = () => {
  resetForm()
  dialogVisible.value = true
}

// 修改按钮操作
const handleUpdate = (row) => {
  resetForm()
  form.id = row.id
  form.name = row.name
  form.code = row.code
  form.remark = row.remark
  dialogVisible.value = true
}

// 查看字典项按钮操作 - 改为弹窗形式
const handleViewItems = (row) => {
  // 保存当前字典信息
  currentCategory.id = row.id
  currentCategory.name = row.name
  
  // 重置查询参数
  itemQueryParams.page = 1
  itemQueryParams.size = 10
  itemQueryParams.categoryId = row.id
  itemQueryParams.name = ''
  itemQueryParams.code = ''
  
  // 打开字典项管理弹窗
  itemDialogVisible.value = true
  
  // 获取字典项列表
  getItemList()
}

// 查询字典项列表
const getItemList = () => {
  if (!currentCategory.id) {
    console.warn('没有选择字典大类，无法获取字典项')
    return
  }
  
  console.log('字典项查询参数:', itemQueryParams)
  itemLoading.value = true
  itemQueryParams.categoryId = currentCategory.id
  
  getDictItemPage(itemQueryParams)
    .then(response => {
      console.log('获取字典项列表成功，完整响应:', response)
      
      // 后端返回的格式: { code: 200, message: "操作成功", data: { list: [], total: 3, pageNum: 1, pageSize: 10 } }
      let records = []
      let totalCount = 0
      
      if (response.data && response.data.list && Array.isArray(response.data.list)) {
        // 后端实际返回的格式
        records = response.data.list
        totalCount = response.data.total || 0
      } else if (response.data && Array.isArray(response.data.records)) {
        // 标准分页格式 { data: { records: [], total: 10 } }
        records = response.data.records
        totalCount = response.data.total || 0
      } else if (Array.isArray(response.data)) {
        // 直接数组格式 { data: [] }
        records = response.data
        totalCount = response.data.length
      } else if (response.records && Array.isArray(response.records)) {
        // 无嵌套的分页格式 { records: [], total: 10 }
        records = response.records
        totalCount = response.total || 0
      }
      
      itemList.value = records
      itemTotal.value = totalCount
      
      console.log('解析后的字典项列表数据:', itemList.value)
    })
    .catch(error => {
      console.error('获取字典项列表失败:', error)
      ElMessage.error('获取字典项列表失败: ' + (error.message || '未知错误'))
    })
    .finally(() => {
      itemLoading.value = false
    })
}

// 字典项查询按钮操作
const handleItemQuery = () => {
  itemQueryParams.page = 1
  getItemList()
}

// 重置字典项查询
const resetItemQuery = () => {
  itemQueryForm.value?.resetFields()
  itemQueryParams.name = ''
  itemQueryParams.code = ''
  itemQueryParams.page = 1
  getItemList()
}

// 字典项每页数量变化
const handleItemSizeChange = (val) => {
  itemQueryParams.size = val
  getItemList()
}

// 字典项页码变化
const handleItemCurrentChange = (val) => {
  itemQueryParams.page = val
  getItemList()
}

// 新增字典项按钮操作
const handleAddItem = () => {
  resetItemForm()
  itemForm.categoryId = currentCategory.id
  itemFormVisible.value = true
}

// 修改字典项按钮操作
const handleUpdateItem = (row) => {
  resetItemForm()
  itemForm.id = row.id
  itemForm.categoryId = currentCategory.id
  itemForm.name = row.name
  itemForm.code = row.code
  itemForm.sort = row.sort
  itemForm.remark = row.remark
  itemFormVisible.value = true
}

// 重置字典项表单
const resetItemForm = () => {
  itemForm.id = undefined
  itemForm.categoryId = currentCategory.id
  itemForm.name = ''
  itemForm.code = ''
  itemForm.sort = 0
  itemForm.remark = ''
  if (itemFormRef.value) {
    itemFormRef.value.resetFields()
  }
}

// 删除字典项按钮操作
const handleDeleteItem = (row) => {
  ElMessageBox.confirm(`确认删除字典项"${row.name}"吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteDictItem(row.id)
      if (res.data) {
        ElMessage.success('删除成功')
        getItemList()
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    } catch (error) {
      console.error('删除失败', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 提交字典项表单
const submitItemForm = () => {
  itemFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    try {
      const saveOrUpdate = itemForm.id ? updateDictItem : createDictItem
      const res = await saveOrUpdate(itemForm)
      
      if (res.data) {
        ElMessage.success(itemForm.id ? '修改成功' : '新增成功')
        itemFormVisible.value = false
        getItemList()
      } else {
        ElMessage.error(res.message || (itemForm.id ? '修改失败' : '新增失败'))
      }
    } catch (error) {
      console.error(itemForm.id ? '修改失败' : '新增失败', error)
      ElMessage.error(itemForm.id ? '修改失败' : '新增失败')
    }
  })
}

// 删除按钮操作
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除字典"${row.name}"吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteDictCategory(row.id)
      if (res.data) {
        ElMessage.success('删除成功')
        getList()
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    } catch (error) {
      console.error('删除失败', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 提交表单
const submitForm = () => {
  categoryFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    try {
      const saveOrUpdate = form.id ? updateDictCategory : createDictCategory
      const res = await saveOrUpdate(form)
      
      if (res.data) {
        ElMessage.success(form.id ? '修改成功' : '新增成功')
        dialogVisible.value = false
        getList()
      } else {
        ElMessage.error(res.message || (form.id ? '修改失败' : '新增失败'))
      }
    } catch (error) {
      console.error(form.id ? '修改失败' : '新增失败', error)
      ElMessage.error(form.id ? '修改失败' : '新增失败')
    }
  })
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;

  // 页面标题
  .page-title-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .page-title {
      display: flex;
      align-items: center;
      font-size: 20px;
      font-weight: 600;
      color: #252525;

      .icon {
        margin-right: 10px;
        font-size: 22px;
        color: #409eff;
      }
    }
  }

  // 卡片样式
  .list-card {
    margin-bottom: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

    .filter-container {
      margin-bottom: 20px;

      .search-form {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        
        .search-item {
          margin-right: 10px;
          margin-bottom: 0;
        }
        
        .action-buttons {
          margin-right: 10px;
          margin-bottom: 0;
          
          .el-button {
            margin-right: 10px;
          }
        }
        
        .add-button-item {
          margin-left: auto;
          margin-bottom: 0;
          
          .add-main-button {
            background-color: #409eff;
            border-color: #409eff;
            color: white;
            font-weight: 500;
          }
        }
      }
    }
  }

  // 分页
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  // 对话框
  :deep(.el-dialog) {
    border-radius: 8px;
    overflow: hidden;

    .el-dialog__header {
      padding: 20px;
      border-bottom: 1px solid #f0f0f0;
      margin-right: 0;
    }

    .el-dialog__body {
      padding: 20px;
    }

    .el-dialog__footer {
      padding: 16px 20px;
      border-top: 1px solid #f0f0f0;
    }
  }

  // 字典项弹窗
  .item-dialog {
    :deep(.el-dialog__body) {
      padding: 16px 20px;
    }

    .item-table-container {
      // 顶部工具栏
      .header-toolbar {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 24px;
        width: 100%;
        
        .search-container {
          width: 100%;
          
          .search-form {
            display: flex;
            align-items: center;
            flex-wrap: wrap;
            
            .search-item {
              margin-right: 10px;
              margin-bottom: 0;
            }
            
            .action-buttons {
              margin-right: 10px;
              margin-bottom: 0;
            }
            
            .add-button-item {
              margin-left: auto;
              margin-bottom: 0;
              
              .add-item-button {
                background-color: #409eff;
                border-color: #409eff;
                color: white;
                font-weight: 500;
              }
            }
          }
        }
      }
    }
  }
}

// 表单样式
:deep(.el-form-item__label) {
  font-weight: 500;
}

// 弹窗底部按钮
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  
  .el-button {
    min-width: 80px;
    padding: 9px 16px;
    border-radius: 4px;
    font-weight: 500;
  }
}
</style> 